<?php
            
use app\model\Record; 
use app\model\Util; 
use app\model\Theme; 
use app\model\Worker; 


/**
 * Desc:
 * Time: 2021/3/16 11:26 上午
 */
class Chance_Page extends PluginWebPage {

    function main($method)
    {
        $method = 'chance_main';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;

        $type = isset($_P['type'])?$_P['type']:'';
        $type_list = $this->getTypeList($themeid,$_C);
        $uid = isset($_P['uid'])?intval($_P['uid']):0;

        $page_total = LotteryModel::getChanceList($themeid,$type,$uid,0,0,0,'','','',true);
        $list = LotteryModel::getChanceList($themeid,$type,$uid,0,$page_start,$page_size);
        $max_chance = (int)$_C['yx_lt_chance_limit'];
        $can_edit_list = LotteryModel::getCanEditList($themeid);
        foreach ($list as $key => $val){
            $list[$key]['can_add'] = true;
            $list[$key]['can_del'] = false;
            $uid = $val['uid'];
            $fans = LotteryModel::getUserInfoById($uid,$themeid);
            $used_lag_toal = LotteryModel::getUserChanceUsed($themeid,$uid);
            $user_used_chance_total = LotteryModel::getUserSystemChance($themeid,$uid);
            $user_flag_total = LotteryModel::getUserFlags($themeid,$uid);
            if ($user_used_chance_total>$user_flag_total && $val['type']=='system'){
                $list[$key]['can_del'] = true;
            }
            if (($used_lag_toal+$fans['jihui'])>=$max_chance){
//                $list[$key]['can_add'] = false;
            }
        }
        $total = $page_total;
        extract(Record::getSearchTime());
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/lottery/chance/main', $return_clicent);
    }

    /**
     * Desc:未使用抽奖机会记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/21 10:49 上午
     */
    function nouse()
    {
        $method = 'no_used';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $total = LotteryModel::getNoUsedUserList($themeid,0,0,'',true);
        if(checksubmit('export_submit', true)){
            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => '会员UID', 'username' => '姓名', 'mobile' => '手机',
                'nickname' => '微信昵称','jihui' => '剩余抽奖次数',
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";

            $sql1 = "select uid from ".tablename(yx_lt_chance)." where chance >0 and themeid=$themeid group by uid";
            $res1 = db_select($sql1);
            $sql2 = "select uid from ".tablename(yx_lt_chance). " where chance =-1 and themeid=$themeid group by uid";
            $res2 = db_select($sql2);
            $add_arr = [];
            $used_arr = [];
            $diff_arr = [];
            foreach ($res1 as $key => $val){
                array_push($add_arr,$val['uid']);
            }
            foreach ($res2 as $k => $v){
                array_push($used_arr,$v['uid']);
            }
            $diff_arr = array_diff($add_arr,$diff_arr);

//            for ($j = 1; $j <= $pagesize; $j++) {
                $ex_page = $_P['ex_page']?$_P['ex_page']:1;
                if (!$diff_arr){
                    $list = [];
                }else{
                    $diff_uid = '';
                    foreach ($diff_arr as $kk => $vv){
                        $diff_uid .= $vv.',';
                    }
                    $diff_uid = '('.rtrim($diff_uid,',').')';
                    $condition = "";
                    if ($search_data){
                        $condition .= " and a.nickname like '".$search_data."'"." or a.mobile like '".$search_data."' " ." or a.username like '".$search_data."' ";
                    }
                    $condition .= " group by b.uid limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";


                    $sql = " select a.uid,a.nickname,a.avatar,a.username,a.mobile,a.jihui from ".tablename(t_fans)." as a ".
                        "left join ".tablename(yx_lt_chance)." as b on a.uid=b.uid and b.themeid=$themeid".
                        " where a.themeid=$themeid and a.uid in $diff_uid ".$condition;
                    $list =  db_select($sql);
                }
                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            $row['nickname'] = str_replace(',','',$row['nickname']);
                            $row['nickname'] = str_replace('"','',$row['nickname']);

                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
               // }
            }
            //新版本导出合并
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            Util::WxJump($_S,$html,'未使用抽奖记录',$themeid,$is_end,$pagesize);
        }



        $list = LotteryModel::getNoUsedUserList($themeid,$page_start,$page_size,$search_data);
        $page_total = $total;
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/lottery/chance/nouse', $return_clicent);
    }

    function fans(){
        $method = 'fans';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $wlist = Worker::getworkerlist($system,$themeid);

        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;


        $type = $_P['type']?intval($_P['type']):0;
        $workerid = isset($_P['workerid'])?$_P['workerid']:0;
        $chance_type = $_P['chance_type']?intval($_P['chance_type']):0;
        $chance_range = $_P['chance_range']?intval($_P['chance_range']):0;
        $chance_num = $_P['chance_num']?intval($_P['chance_num']):0;
        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        $search_array = [
             'type' => $type,
             'workerid' => $workerid,
             'chance_type' => $chance_type,
             'chance_range' => $chance_range,
             'chance_num' => $chance_num,
             'search_data' =>$search_data?'%'.$search_data.'%':''
        ];

        $chance_limit = $config['yx_lt_chance_limit'];

        $count_sql = "SELECT count(DISTINCT c.uid,r.id and CASE WHEN  r.status=1 THEN 1 END) as pay_num
                      from ".tablename(yx_lt_chance)." as c 
                      LEFT JOIN ".tablename(t_record)." AS r ON c.uid=r.uid and r.themeid=$themeid
                      WHERE c.themeid={$themeid}";

        $count_data = db_find($count_sql);
        $all_fans_num = db_fetchcolumn("select count(distinct uid) from ".tablename(yx_lt_chance)." where themeid=$themeid");
        $can_fans_num = db_fetchcolumn("select count(distinct uid) from ".tablename(yx_lt_chance)." where chance >0 and themeid=$themeid");
        $used_user_num = db_fetchcolumn("select count(distinct uid) from ".tablename(yx_lt_chance). " where chance =-1 and themeid=$themeid");

        $noused_fans_num = max(0,($can_fans_num - $used_user_num));
        $nopay_num = $all_fans_num - $count_data['pay_num'];
        $type_list = [
            ['type'=>0,'title'=>'全部','total' => $can_fans_num],
            ['type'=>1,'title'=>'已支付','total' => $count_data['pay_num']],
            ['type'=>2,'title'=>'未支付','total' => $nopay_num],
            ['type'=>3,'title'=>'从未抽过 ','total' => $noused_fans_num],
            ['type'=>4,'title'=>'已抽','total' => $used_user_num]
        ];

        $type_arr = LotteryModel::getFlagTypeCount($themeid);
        $prize_arr = LotteryModel::getPrizeFlagCount($themeid);

        $total = LotteryModel::getLotteryUserList($system,$config,$themeid,0,0,$search_array,true);

        if(checksubmit('export_submit', true)){
            $count = $total;
            $header = array(
                'uid' => 'UID',
                'nickname' => '昵称',
                'username' => '姓名',
                'mobile' => '电话',
                'get_num' => '机会获得',
                'use_num' => '机会使用',
                'jihui' => '机会剩余',
                'prize_name' => '奖品',
                'pay_status' => '订单状态',
                'worker' => '员工',
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";

            $ex_page_size = 2000;
            $ex_page_index = max(1,intval($_P['ex_page']));
            $pagesize = ceil($total/$ex_page_size);
            $ex_page_start = ($ex_page_index-1)*$ex_page_size;
            $list = LotteryModel::getLotteryUserList($system,$config,$themeid,$ex_page_start,$ex_page_size,$search_array);
            if (!empty($list)) {
                $size = ceil(count($list) / 500);
                for ($i = 0; $i < $size; $i++) {
                    $buffer = array_slice($list, $i * 500, 500);
                    foreach ($buffer as $row) {
                        $row['nickname'] = str_replace(',','',$row['nickname']);
                        $row['nickname'] = str_replace('"','',$row['nickname']);
                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        if (isset($data)){
                            $user[] = implode("\t ,", $data) . "\t ,";
                            unset($data);
                        }
                    }
                    $html .= implode("\n", $user)."\n";
                    unset($user);
                }
            }
            //新版本导出合并
            $is_end = 0;
            if($ex_page_index==$pagesize){
                $is_end = 1;
            }
            Util::WxJump($_S,$html,'抽奖参与用户记录',$themeid,$is_end,$pagesize);
        }
        $list = LotteryModel::getLotteryUserList($system,$config,$themeid,$page_start,$page_size,$search_array);
        $page_total = $total;
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/lottery/chance/nouse', $return_clicent);
    }

    function search()
    {
        $method = 'chance_main';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        if (empty($_P['createtime']['start'])){
            $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$start_day);
        }else{
            $start_day =  $_P['createtime']['start'];
        }
        $end_day = empty($_P['createtime']['end']) ? date('Y-m-d H:i:s',TIMESTAMP): $_P['createtime']['end'] ;

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }
        $title = isset($_P['title'])?$_P['title']:'';
        $type = isset($_P['type'])?$_P['type']:'';
        $type_list = $this->getTypeList($themeid,$_C);
        $can_edit_list = LotteryModel::getCanEditList($themeid);
//        $lists = LotteryModel::getChanceList($themeid,'',0,0,0,0,$search_data,$start_day,$end_day);
//        $total = count($lists);

        $list = LotteryModel::getChanceList($themeid,'',0,0,$page_start,$page_size,$search_data,$start_day,$end_day);

        $max_chance = (int)$_C['yx_lt_chance_limit'];
        foreach ($list as $key => $val){
            $list[$key]['can_add'] = true;
            $list[$key]['can_del'] = false;
            $uid = $val['uid'];
            $fans = LotteryModel::getUserInfoById($uid,$themeid);
            $used_lag_toal = LotteryModel::getUserChanceUsed($themeid,$uid);
            $user_used_chance_total = LotteryModel::getUserSystemChance($themeid,$uid);
            $user_flag_total = LotteryModel::getUserFlags($themeid,$uid);
            if ($user_used_chance_total>$user_flag_total && $val['type']=='system'){
                $list[$key]['can_del'] = true;
            }
            if (($used_lag_toal+$fans['jihui'])>=$max_chance){
//                $list[$key]['can_add'] = false;
            }
        }


        $page_total = count($list);
        extract(Record::getSearchTime());
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/lottery/chance/main', $return_clicent);
    }

    function del()
    {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = $_P['themeid'];
        $uid = $_P['uid'];
        $cid = $_P['cid'];

        $where = ['uid'=>$uid,'themeid'=>$themeid,'c_id'=>$cid];
        $res = LotteryModel::deleteChanceFlag($where);
        if (!$res){
            show_json(0,['msg'=>'删除失败']);
        }else{
            show_json(1,['msg'=>'删除成功']);
        }

        $old_data= ['uid'=>$uid];
        $type_txt = '用户删除抽奖机会';
        writelog($themeid,$type_txt,$old_data,[],$_G['username']);

    }

    /**
     * Desc:获取抽奖机会的类型和数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/30 4:17 下午
     * @param $themeid
     * @param $config
     * @return string[][]
     */
    function getTypeList($themeid,$config)
    {
        $type_list = [
            ['type'=>'','title'=>'全部'],
            ['type'=>'system','title'=>'已抽'],
        ];
        //未报名可抽
//        if ($config['yx_lt_no_sign_up']) {
//            $temp_arr = ['type'=>'no_sign_up','title'=>'未报名'];
//            array_push($type_list,$temp_arr);
//        }
        //报名可抽
        if ($config['yx_lt_self_order']) {
            $temp_arr = ['type'=>'self_order','title'=>'自己下单'];
            array_push($type_list,$temp_arr);
        }
        //好友报名
        if ($config['yx_lt_friend_order']) {
            $temp_arr = ['type'=>'friend_order','title'=>'好友下单'];
            array_push($type_list,$temp_arr);
        }
        //分享朋友圈
        if ($config['yx_lt_first_share_moment'] || $config['yx_lt_second_share_moment'] || $config['yx_lt_third_share_moment']) {
            $temp_arr = ['type'=>'share_moments','title'=>'分享朋友圈'];
            array_push($type_list,$temp_arr);
        }
        //好友到访
        if ($config['yx_lt_friend_view']) {
            $temp_arr = ['type'=>'friend_view','title'=>'好友到访'];
            array_push($type_list,$temp_arr);
        }
        //好友助力
        if ($config['yx_lt_friend_help']) {
            $temp_arr = ['type'=>'friend_help','title'=>'好友助力'];
            array_push($type_list,$temp_arr);
        }
        //定时奖励
        if ($config['yx_lt_timeset']) {
            $temp_arr = ['type'=>'timeset','title'=>'定时奖励'];
            array_push($type_list,$temp_arr);
        }
        //幸运星
        if ($config['yx_lt_lucky_star']) {
            $temp_arr = ['type'=>'lucky_star','title'=>'幸运星'];
            array_push($type_list,$temp_arr);
        }
        //管理员增加抽奖机会
        $temp_arr = ['type'=>'system_add','title'=>'后台增加抽奖机会'];
        array_push($type_list,$temp_arr);
        foreach ($type_list as $key => $val) {
            $list = LotteryModel::getChanceList($themeid,$val['type']);
            $total = count($list);
            $type_list[$key]['total'] = $total;
        }
        return $type_list;
    }

    /**
     * Desc:补录中奖记录并减少机会
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2023/2/9 08:34
     */
    function addLtFlagAndReduceChance()
    {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $c_id = $_P['add_c_id']?$_P['add_c_id']:0;
        $p_id = $_P['p_id']?$_P['p_id']:0;
        $uid = $_P['add_uid']?$_P['add_uid']:0;
        $themeid = $_P['themeid'];
        if (!$p_id || !$uid){
            show_json(0,['msg'=>'手动录入中奖记录失败，请检查后重试']);
            die();
        }
        $chance_item = db_get(yx_lt_chance,['themeid'=>$themeid,'c_id'=>$c_id]);
        if (!$chance_item){
            show_json(0,['msg'=>'用户抽奖记录不存在']);
            die();
        }


        //用户表 剩余抽检次数减 抽奖机会表加
        $fans = LotteryModel::getUserInfoById($uid,$themeid);
        $chance_num = $fans['jihui'];
        $new_chance_num = $chance_num-1;
        if ($new_chance_num>=0){
            $res = LotteryModel::updateFansInfo($fans['uid'],$themeid,['jihui'=>$new_chance_num]);
        }
        $prize_item = db_get(yx_lt_prize,['p_id'=>$p_id,'themeid'=>$themeid]);
        if ($prize_item['qty']>1){
            $update_lt_item_sql = "update ".tablename(yx_lt_prize)." set qty=qty-1,out_qty=out_qty + 1 where p_id='".$p_id."' and themeid='$themeid'";
        }else{
            $update_lt_item_sql = "update ".tablename(yx_lt_prize)." set out_qty=out_qty + 1 where p_id='".$p_id."' and themeid='$themeid'";
        }
        db_find($update_lt_item_sql);


        //中奖表插入记录
        $record_data = [
            'p_id'=>$p_id,
            'uid'=>$uid,
            'themeid'=>$themeid,
            'convert_code'=>GetRandConvertCode(),
            'status'=>1,
            'created_at'=>$chance_item['created_at']
        ];
        $res = LotteryModel::insertLtFlag($record_data);
        if (!$res){
            show_json(0,['msg'=>'手动录入中奖记录失败']);
        }else{
            show_json(1,['msg'=>'手动录入中奖记录成功']);
        }
    }
}